<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="search()">
			<el-form-item label="申报阶段" prop="applyStage">
				<el-select v-model="state.queryForm.applyStage" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in applyStage" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="申报状态" prop="applyStatus">
				<el-select v-model="state.queryForm.applyStatus" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in applyStatus" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="申报结论" prop="applyResult">
				<el-select v-model="state.queryForm.applyResult" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in applyResult" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="类别" prop="standardCategory">
				<el-select v-model="state.queryForm.standardCategory" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in standardCategory" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入" clearable>
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px">
							<el-option label="项目名称" value="1" />
							<el-option label="主编单位" value="2" />
							<el-option label="主管单位" value="3" />
							<el-option label="联系人" value="4" />
							<el-option label="申请年份" value="5" />
						</el-select>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="类型" prop="standardType">
				<el-select v-model="state.queryForm.standardType" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in standardType" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-space style="width: 100%; justify-content: flex-end">
			<el-space>
				<el-button v-auth="'M001_A'" type="primary" @click="handleAddNew">申报</el-button>
			</el-space>
		</el-space>
		<el-table v-loading="state.dataListLoading" :data="dataList" stripe class="layout-table" border @selection-change="selectionChangeHandle">
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column prop="standardProjectName" label="申报项目" header-align="center" align="center" resizable sortable></el-table-column>
			<el-table-column
				prop="editorUnitName"
				label="主编单位"
				header-align="center"
				align="center"
				show-overflow-tooltip
				resizable
				sortable
			></el-table-column>
			<el-table-column
				prop="contacts"
				label="联系人"
				header-align="center"
				align="center"
				width="120"
				show-overflow-tooltip
				resizable
				sortable
			></el-table-column>
			<el-table-column
				prop="projectFunding"
				label="申请经费(万元)"
				header-align="center"
				align="center"
				width="120"
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="applyYear" label="申报年度" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="applyStage" label="申报阶段" header-align="center" align="center" resizable sortable>
				<template #default="scope">
					<span>{{ dictionaryStore.getDictionaryName('T001', scope.row.applyStage) }}</span>
					<!-- <span v-if="scope.row.applyStage == 6">住建委审核</span> -->
				</template>
			</el-table-column>
			<el-table-column prop="applyStatus" label="申报状态" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<div style="display: flex; align-items: center; justify-content: center">
						<span v-if="scope.row.applyStatus">{{ dictionaryStore.getDictionaryName('T004', scope.row.applyStatus) }}</span>
						<el-tooltip v-if="scope.row.applyStatus == '6'" :content="scope.row.returnOpinion" placement="top">
							<el-icon :size="16" color="#1491FF" style="cursor: pointer; margin-left: 5px">
								<Warning />
							</el-icon>
						</el-tooltip>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="applyResult" label="申报结果" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<span v-if="scope.row.applyResult" type="success">{{ dictionaryStore.getDictionaryName('T013', scope.row.applyResult) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="120">
				<template #default="scope">
					<el-icon
						v-if="scope.row.applyStatus == '0'"
						v-auth="'M001_U'"
						:size="16"
						color="#1491FF"
						title="编辑"
						style="cursor: pointer; margin: 0 6px"
						@click="handleEdit(scope.row)"
					>
						<Edit />
					</el-icon>
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="handleView(scope.row)">
						<View />
					</el-icon>
					<el-icon
						v-if="scope.row.applyStage == '0'"
						v-auth="'M001_D'"
						:size="16"
						color="#1491FF"
						title="删除"
						style="cursor: pointer; margin: 0 6px"
						@click="handleDel(scope.row)"
					>
						<Delete />
					</el-icon>
					<el-icon
						v-if="scope.row.applyStage != '0'"
						:size="16"
						color="#1491FF"
						:title="scope.row.standardProjectName + '项建书pdf下载'"
						style="cursor: pointer; margin: 0 6px"
						@click="handleExport(scope.row)"
					>
						<Document />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<addDialog v-model="showAddDialog" :edit-id="editId" :is-view="isView" :is-audit="false" @submit-success="addSuccess"> </addDialog>
	</el-card>
</template>
<script setup lang="ts">
import { delDeclare, getAddList, getDeadline } from '@/api/declare'
import { Drafter, StandardProjectInfo, StandardProjectProposal, Unit } from '@/interface/declare'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import addDialog from './components/addDialog.vue'

const route = useRoute()
const pendingStatus = route.query.pendingStatus

const dictionaryStore = useDictionaryStore()
const userStore = useUserStore()

const applyStage = dictionaryStore.getDictionaryByCode('T001')
const applyStatus = dictionaryStore.getDictionaryByCode('T004')
const applyResult = dictionaryStore.getDictionaryByCode('T013')
const standardCategory = dictionaryStore.getDictionaryByCode('T005')
const standardType = dictionaryStore.getDictionaryByCode('T006')
const professionalKeyFieldsArr = dictionaryStore.getDictionaryByCode('T003')

const state = reactive({
	queryForm: {
		applyStage: null,
		applyStatus: null,
		applyResult: null,
		standardCategory: null,
		standardType: null,
		standardProjectName: null,
		editorUnitName: null,
		responsibleOrgName: null,
		contactName: null,
		applyYear: null,
		responsiblePerson: null,
		mainDrafterName: null,
		pendingStatus: pendingStatus || null
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null
})

interface IListDataType {
	applyResult: string
	applyStage: string
	applyStatus: string
	applyYear: string
	contacts: string
	editorUnitName: string
	id: string
	opinions: null
	permission: null
	projectFunding: number
	responsibleOrgName: string
	standardProjectName: string
}

const dataList = ref<IListDataType[]>([])
const showAddDialog = ref<boolean>(false)
const editId = ref<string>('')
const isView = ref<boolean>(false)
const isAudit = ref<boolean>(false)
const isDead = ref<boolean>(false)

const pdfInfo = ref({
	standardProjectInfo: {} as StandardProjectInfo,
	standardProjectProposal: {} as StandardProjectProposal,
	projectMainDrafterList: [] as Drafter[],
	projectEditorUnitList: [] as Unit[]
})

watch(
	() => showAddDialog.value,
	newVal => {
		if (newVal == false) {
			editId.value = ''
			isView.value = false
			isAudit.value = false
		}
	}
)

const getDataList = () => {
	state.queryForm.standardProjectName = ''
	state.queryForm.editorUnitName = ''
	state.queryForm.responsibleOrgName = ''
	state.queryForm.contactName = ''
	state.queryForm.applyYear = ''
	if (state.keyword && !state.keyType) {
		ElMessage.error('请选择关键词类型')
		return
	}
	switch (state.keyType) {
		case '1':
			state.queryForm.standardProjectName = state.keyword
			break
		case '2':
			state.queryForm.editorUnitName = state.keyword
			break
		case '3':
			state.queryForm.responsibleOrgName = state.keyword
			break
		case '4':
			state.queryForm.contactName = state.keyword
			break
		case '5':
			state.queryForm.applyYear = state.keyword
			break
	}
	state.dataListLoading = true
	getAddList({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		dataList.value = res.data.list || []
		state.total = res.data.total || 0
	})
}

const search = () => {
	state.pageNum = 1
	getDataList()
}

const reset = () => {
	state.queryForm.applyResult = null
	state.queryForm.applyStage = null
	state.queryForm.applyStatus = null
	state.queryForm.standardCategory = null
	state.queryForm.standardType = null
	state.queryForm.standardProjectName = null
	state.queryForm.editorUnitName = null
	state.queryForm.responsibleOrgName = null
	state.queryForm.contactName = null
	state.queryForm.applyYear = null
	state.queryForm.pendingStatus = null
	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	getDataList()
}

const handleAddNew = () => {
	if (!isDead.value) {
		showAddDialog.value = true
		editId.value = ''
		isAudit.value = true
	} else {
		ElMessage.error('超过申报截止时间 ，不可申报！')
	}
}

const handleEdit = (row: any) => {
	editId.value = row.id
	showAddDialog.value = true
}

const handleView = (row: any) => {
	isView.value = true
	editId.value = row.id
	showAddDialog.value = true
}

const selectionChangeHandle = () => {}
const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}

const addSuccess = (e: any) => {
	editId.value = ''
	showAddDialog.value = false
	getDataList()
}

const handleDel = (row: any) => {
	ElMessageBox.confirm(`是否删除'${row.standardProjectName}'的申报信息,删除后无法恢复!`, '温馨提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			delDeclare({
				id: row.id
			}).then(() => {
				getDataList()
				ElMessage.success('删除申报成功')
			})
		})
		.catch(() => {})
}

const handleExport = (row: any) => {
	axios({
		method: 'post',
		url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/standardProject/exportPdf',
		headers: {
			'Content-Type': 'application/json;charset=UTF-8',
			Authorization: userStore.token
		},
		data: {
			id: row.id
		},
		responseType: 'blob'
	})
		.then(response => {
			ElMessage.success('操作成功，文件已开始下载')
			const blob = new Blob([response.data], {
				type: 'application/pdf'
			})
			const url = window.URL.createObjectURL(blob)
			const a = document.createElement('a')
			a.href = url
			a.download = `${row.standardProjectName}项目建议书.pdf`
			a.click()
			window.URL.revokeObjectURL(url)
		})
		.catch(error => {
			console.error('导出失败:', error)
		})
}

const getTime = (year: string) => {
	getDeadline({
		settingYear: year,
		activeStatus: 0,
		stageCode: 'StandardApply',
		remark: '',
		preparationType: '',
		pageIndex: 1,
		pageSize: 10
	}).then(res => {
		const data = res.data.list || []
		const deadLineTime = data.find(item => item.stageCode === 'StandardApply' && item.activeStatus === 0).deadLineTime || ''
		if (deadLineTime) {
			//判断当前时间大于deadLineTime，则为已截止
			const nowTime = new Date().getTime()
			const deadLine = new Date(deadLineTime).getTime()
			if (nowTime > deadLine) {
				isDead.value = true
			} else {
				isDead.value = false
			}
		} else {
			isDead.value = false
		}
	})
}

onMounted(() => {
	getDataList()
	const year = new Date().getFullYear()
	getTime(year.toString())
})
</script>
<style lang="scss" scoped>
.title {
	font-size: 20px;
	text-align: center;
}

.subtitle {
	font-size: 16px;
	margin: 30px 0 10px;
}

.form {
	display: flex;
	flex-wrap: wrap;

	.item {
		display: flex;
		align-items: center;
		min-width: 33.33%;

		.label {
			font-size: 14px;
			height: 30px;
			line-height: 30px;
		}

		.value {
			padding: 2px 20px 2px 5px;
			border-bottom: solid 1px #333;
			font-size: 14px;
			margin-right: 50px;
			flex: 1;
			height: 30px;
			line-height: 30px;
		}
	}
}

.form2 {
	margin-top: 20px;

	.label {
		line-height: 20px;
	}

	.value {
		border-bottom: solid 1px #333;
		font-size: 14px;
		line-height: 28px;
	}
}
</style>
